import { Pages } from "./to/pages/Pages"
import { toHomeLiveLive } from "./to/toHomeLive"
import { useStorage } from "./utils/useStorage"
import { parseRoomInfo } from "./utils/parseRoomInfo"
const storage = useStorage()

export function homeLiveLiveSearch(index: number = 0) {
    const start = storage.get('start', true)
    if (!start) return;
    const homeLiveLiveCtx = toHomeLiveLive()
    if (!homeLiveLiveCtx) {
        return false;
    }
    if (homeLiveLiveCtx.get('currentPage') !== Pages.homeLiveLive) {
        return false;
    }
    events.emit('log', `正在搜索第${index + 1}`)
    const livesList = homeLiveLiveCtx.get<any[]>(`livesList`)
    if (index >= livesList.length) {
        return true;
    }
    const isLast = index === (livesList.length - 1)
    if (livesList && livesList.length > 0 && index < livesList.length) {
        const item = livesList.find((it, i) => {
            if (index !== i) return false;
            if (!it) return false;
            const redCard = it.redCard;
            if (redCard) {
                const bounds = redCard.bounds()
                return homeLiveLiveCtx.isRed(bounds)
            }
            return false;
        })
        if (!item) {
            return isLast;
        }
        item.click()
        events.emit('log', '检查直播间')
        sleep(5000)
        parseRoomInfo()
    }
    sleep(3000)
    toHomeLiveLive()
    return isLast;
}